<template>
  <view class="login_page">
    <u-navbar fixed placeholder bgColor="transparent">
      <template #left>
        <text class="nav_title">登录</text>
      </template>
    </u-navbar>
    <image src="@/static/img/login/login_bg.png" class="login_bg"></image>
    <view class="content" :style="{ height: `calc(100% - ${navBarHeight}px)` }">
      <view class="welcome">
        <view>您好，</view>
        <view>欢迎使用商户端</view>
      </view>
      <view class="form">
        <view class="tabs_box">
          <u-tabs
            :list="tab_list"
            :scrollable="false"
            :current="activeTab"
            lineColor="#148B81"
            :lineWidth="32"
            :lineHeight="4"
            :inactiveStyle="{
              'font-size': '32rpx',
              'font-weight': 500,
              color: '#636363',
            }"
            :activeStyle="{
              'font-size': '32rpx',
              'font-weight': 500,
              'font-weight': 500,
              color: '#333',
            }"
            @click="(event) => this.changeTab(event.index)"
          >
          </u-tabs>
        </view>
        <!-- 登录 -->
        <view v-if="activeTab === 0" class="login_box">
          <uni-forms
            ref="customForm"
            :modelValue="loginForm"
            label-position="top"
            :rules="customRules"
          >
            <uni-forms-item required name="username">
              <template #label>
                <view class="form_label">
                  <image src="@/static/img/login/phone_icon.png" mode="widthFix"></image>
                  <text>手机号</text>
                </view>
              </template>
              <uni-easyinput
                v-model="loginForm.username"
                primaryColor="#0E9589"
                placeholder="请输入手机号"
                :clearable="false"
              />
            </uni-forms-item>
            <uni-forms-item required name="password">
              <template #label>
                <view class="form_label">
                  <image src="@/static/img/login/password_icon.png" mode="widthFix"></image>
                  <text>密码</text>
                </view>
              </template>
              <uni-easyinput
                v-model="loginForm.password"
                type="password"
                primaryColor="#0E9589"
                placeholder="请输入密码"
                :clearable="false"
              />
            </uni-forms-item>
            <uni-forms-item
              required
              name="code"
              style="position: relative"
            >
              <template #label>
                <view class="form_label">
                  <image src="@/static/img/login/verify_icon.png" mode="widthFix"></image>
                  <text>验证码</text>
                </view>
              </template>
              <uni-easyinput
                v-model="loginForm.code"
                primaryColor="#0E9589"
                placeholder="请输入验证码"
                maxlength="4"
                :clearable="false"
              />
              <view class="login-code">
                <image
                  :src="codeUrl"
                  @click="getCode"
                  class="login-code-img"
                ></image>
              </view>
            </uni-forms-item>
          </uni-forms>
          <u-button type="primary" shape="circle" text="登录" @click="submitLogin('customForm')"></u-button>

          <view class="xieyi">
            <uni-data-checkbox
              multiple
              v-model="loginForm.isRead"
              @change="changeBox"
              selectedColor="#0E9589"
              :localdata="sexs"
            ></uni-data-checkbox>
            <view>
              我已阅读
              <text @click="handleUserAgreement" class="text_color">用户协议</text>
              和
              <text @click="handlePrivacy" class="text_color">隐私政策</text>
              并理解相关条款内容
            </view>
          </view>
        </view>
        <!-- 注册 -->
        <view v-if="activeTab === 1" class="regist_box">
          <uni-forms
            ref="registerFormRef"
            :modelValue="registerForm"
            label-position="top"
            :rules="registerRules"
          >
            <uni-forms-item required name="phoneNumber">
              <template #label>
                <view class="form_label">
                  <image src="@/static/img/login/phone_icon.png" mode="widthFix"></image>
                  <text>手机号</text>
                </view>
              </template>
              <uni-easyinput
                v-model="registerForm.phoneNumber"
                primaryColor="#0E9589"
                placeholder="请输入手机号"
                :clearable="false"
              />
            </uni-forms-item>
            <uni-forms-item required name="password">
              <template #label>
                <view class="form_label">
                  <image src="@/static/img/login/password_icon.png" mode="widthFix"></image>
                  <text>密码</text>
                </view>
              </template>
              <uni-easyinput
                v-model="registerForm.password"
                type="passport"
                primaryColor="#0E9589"
                placeholder="请输入密码"
                :clearable="false"
                @input="inputPassWord"
              />
            </uni-forms-item>
            <uni-forms-item required name="confirmPassword">
              <template #label>
                <view class="form_label">
                  <image src="@/static/img/login/password_icon.png" mode="widthFix"></image>
                  <text>确认密码</text>
                </view>
              </template>
              <uni-easyinput
                v-model="registerForm.confirmPassword"
                type="passport"
                primaryColor="#0E9589"
                placeholder="请输入密码"
                :clearable="false"
              />
            </uni-forms-item>
            <uni-forms-item required name="email">
              <template #label>
                <view class="form_label">
                  <image src="@/static/img/login/email_icon.png" mode="widthFix"></image>
                  <text>邮箱</text>
                </view>
              </template>
              <uni-easyinput
                v-model="registerForm.email"
                primaryColor="#0E9589"
                placeholder="请输入邮箱"
                :clearable="false"
              />
            </uni-forms-item>
          </uni-forms>
          <u-button type="primary" shape="circle" text="确认" @click="registerLogin('registerFormRef')"></u-button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import {getCodeImg, register} from "@/api/login";

export default {
  data() {
    return {
      tab_list: [
        { name: '登录' },
        { name: '注册' }
      ],
      activeTab: 0,
      // 注册
      registerForm: {
        phoneNumber: "",
        password: "",
        confirmPassword: "",
        email: "",
        platform: "Business",
      },

      registerRules: {
        // 手机号
        phoneNumber: {
          rules: [
            {
              required: true,
              errorMessage: "请填写手机号码",
            },
            {
              validateFunction: function (rule, value, data, callback) {
                let iphoneReg =
                    /^(13[0-9]|14[1579]|15[0-3,5-9]|16[6]|17[0123456789]|18[0-9]|19[89])\d{8}$/;
                if (!iphoneReg.test(value)) {
                  callback("手机号码格式不正确，请重新填写");
                }
              },
            },
          ],
        },
        // 密码
        password: {
          rules: [
            {
              required: true,
              errorMessage: "密码不能为空",
            },
          ],
        },
        confirmPassword: {
          rules: [
            {
              required: true,
              errorMessage: "确认密码不能为空",
            },
            {
              validateFunction: function (rule, value, data, callback) {
                let pwd = uni.getStorageSync("pwd_key");
                if (value !== pwd) {
                  callback("两次密码输入不同，请重新输入");
                }
              },
            },
          ],
        },
        email: {
          rules: [
            {
              required: true,
              errorMessage: "请填写邮箱",
            },
            {
              validateFunction: function (rule, value, data, callback) {
                let emailReg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
                if (!emailReg.test(value))
                  return callback("请输入正确的邮箱格式！");
                return true;
              },
            },
          ],
        },
      },
      // 登录
      // 单选数据源
      sexs: [
        {
          text: "",
          value: 1,
        },
      ],
      codeUrl: "",
      captchaEnabled: true,
      // 用户注册开关
      register: false,
      globalConfig: getApp().globalData.config,
      loginForm: {
        username: "",
        password: "",
        code: "",
        uuid: "",
        platform: "Business",
        isRead: 0,
      },
      // 自定义表单校验规则
      customRules: {
        username: {
          rules: [
            {
              required: true,
              errorMessage: "手机号不能为空",
            },
            {
              validateFunction: function (rule, value, data, callback) {
                let iphoneReg =
                    /^(13[0-9]|14[1579]|15[0-3,5-9]|16[6]|17[0123456789]|18[0-9]|19[89])\d{8}$/;
                if (!iphoneReg.test(value)) {
                  callback("手机号码格式不正确，请重新填写");
                }
              },
            },
          ],
        },
        password: {
          rules: [
            {
              required: true,
              errorMessage: "密码不能为空",
            },
          ],
        },
        code: {
          rules: [
            {
              required: true,
              errorMessage: "验证码不能为空",
            },
          ],
        },
      },
    };
  },
  created() {
    this.getCode();
  },
  computed: {
    navBarHeight() {
      const platform = uni.getSystemInfoSync().platform
      const statusBarHeight = uni.getSystemInfoSync().statusBarHeight
      let navHeight = 0
      if (['ios', 'devtools'].includes(platform)) {
        navHeight = 44
      } else {
        navHeight = 48
      }
      return navHeight + statusBarHeight
    }
  },
  methods: {
    // 注册时，保存密码
    inputPassWord() {
      uni.setStorageSync("pwd_key", this.registerForm.password);
    },
    // 注册按钮
    registerLogin(ref) {
      this.$refs[ref]
          .validate()
          .then((res) => {
            console.log("success", res);
            console.log(this.registerForm);
            const data = {
              phonenumber: this.registerForm.phoneNumber,
              password: this.registerForm.password,
              email: this.registerForm.email,
              platform: this.registerForm.platform,
            };
            register(data)
                .then((res) => {
                  if (res.code === 200) {
                    this.changeTab(0);
                    this.registerForm = {
                      phoneNumber: "",
                      password: "",
                      confirmPassword: "",
                      email: "",
                      platform: "Business",
                    };
                  }
                })
                .catch((err) => {
                  console.log(err);
                });
          })
          .catch((err) => {
            console.log("err", err);
          });
    },
    // 选择协议
    changeBox(e) {
      console.log(e);
    },
    submitLogin(ref) {
      if (!this.loginForm.isRead.length) {
        uni.showToast({
          title: `请先同意用户协议`,
          icon: "exception",
        });
        return;
      }
      this.$refs[ref]
          .validate()
          .then((res) => {
            console.log("success", res);
            this.pwdLogin();
          })
          .catch((err) => {
            console.log("err", err);
          });
    },
    changeTab(index) {
      this.activeTab = index;
    },
    // 隐私协议
    handlePrivacy() {
      let site = this.globalConfig.appInfo.agreements[0];
      this.$tab.navigateTo(
          `/pages/common/webview/index?title=${site.title}&url=${site.url}`
      );
    },
    // 用户协议
    handleUserAgreement() {
      let site = this.globalConfig.appInfo.agreements[1];
      this.$tab.navigateTo(
          `/pages/common/webview/index?title=${site.title}&url=${site.url}`
      );
    },
    // 获取图形验证码
    getCode() {
      getCodeImg().then((res) => {
        this.captchaEnabled =
            res.captchaEnabled === undefined ? true : res.captchaEnabled;
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.loginForm.uuid = res.uuid;
        }
      });
    },
    // 密码登录
    async pwdLogin() {
      this.$store
          .dispatch("Login", this.loginForm)
          .then((res) => {
            console.log(res);
            this.$modal.closeLoading();
            this.loginSuccess();
          })
          .catch((err) => {
            console.log(err);
            if (this.captchaEnabled) {
              this.getCode();
            }
          });
    },
    // 登录成功后，处理函数
    loginSuccess() {
      // 设置用户信息
      this.$store.dispatch("GetInfo").then((res) => {
        this.$tab.reLaunch("/pages/settled/settled");
      });
    },
  },
};
</script>

<style lang="scss">
.uni-forms-item__label {
  width: 100% !important;
  font-size: 32rpx !important;
  font-weight: 500 !important;
  color: #333333 !important;
  padding: 0 !important;
}

.is-input-border {
  width: 654rpx !important;
  height: 88rpx !important;
  background: #f5f6f8 !important;
  border-radius: 224rpx 224rpx 224rpx 224rpx !important;
}

.uni-easyinput__content-input {
  font-size: 28rpx !important;
  font-weight: 400 !important;
  color: #999999 !important;
}

.uni-easyinput {
  width: 88% !important;
}

.uni-easyinput__placeholder-class {
  font-size: 28rpx !important;
  font-weight: 400 !important;
  color: #999999 !important;
}

::v-deep .uni-forms-item {
  margin-bottom: 50rpx !important;
}

.checkbox__inner {
  border-radius: 50% !important;
}

.checklist-box {
  margin: 0 !important;
}

.check_box {
  width: 32rpx;
  height: 32rpx;
  margin-right: 16rpx;
}
</style>

<style lang="scss" scoped>
.login_page {
  height: 100vh;
  width: 100vw;
  position: relative;

  .nav_title {
    font-size: 40rpx;
    color: #fff;
    font-weight: 400;
  }

  .login_bg {
    height: 100%;
    width: 100%;
    position: absolute;
    top: 0;
    left: 0;
    z-index: -1;
  }

  .content {
    display: flex;
    flex-direction: column;

    .welcome {
      height: 160rpx;
      padding: 32rpx;
      display: flex;
      flex-direction: column;
      justify-content: flex-end;

      font-size: 40rpx;
      font-family: HarmonyOS Sans SC-Regular, HarmonyOS Sans SC;
      font-weight: 400;
      color: #FFFFFF;
      line-height: 64rpx;
      text-shadow: 0px 6px 4px rgba(0, 0, 0, 0.302);
    }

    .form {
      flex: 1;
      width: 100%;
      border-radius: 48rpx 48rpx 0 0;
      background: #fff;
      opacity: 0.9;
      padding: 0 48rpx 48rpx;
      box-sizing: border-box;
      display: flex;
      flex-direction: column;
      align-items: center;
      .tabs_box {
        width: 100%;
        margin-bottom: 40rpx;
      }
      .login_box, .regist_box {
        width: 100%;
      }
      .form_label {
        display: flex;
        align-items: center;
        margin-bottom: 16rpx;
        image {
          height: 25rpx;
          width: 32rpx;
          margin-right: 16rpx;
        }
        text {
          font-size: 32rpx;
          font-weight: 500;
          color: #333333;
        }
      }
      .xieyi {
        margin-top: 40rpx;
        display: flex;
        font-size: 24rpx;
        align-items: center;
        color: #c2c2c2;
        .text_color {
          color: #a8a8a8;
        }
      }
    }
  }
  .login-code-img {
    position: absolute;
    z-index: 10;
    top: 50%;
    transform: translateY(-50%);
    right: 28rpx;
    width: 140rpx;
    height: 56rpx;
  }
}
</style>
